package com.bl.nio.client;

import com.bl.nio.client.handler.ClientHandler;
import com.bl.nio.client.handler.HeartbeatHandler;
import com.bl.nio.common.constant.Const;
import com.bl.nio.common.entity.SocketClient;
import com.bl.nio.common.entity.Transport;
import com.bl.nio.common.handler.IEventHandler;

import java.io.IOException;
import java.net.Socket;
import java.util.Timer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 作者 : blownsow
 * @version 版本: 1.0
 * @date 创建时间 : 2019/12/7 11:23
 * @describe 类描述:
 */
public class NioClient {
    private SocketClient client;

    private IEventHandler eventHandler;

    private ExecutorService executorService = Executors.newCachedThreadPool();

    public NioClient(String host,int port,IEventHandler eventHandler) throws IOException {
        Transport transport = new Transport(host, port);

        Socket socket = transport.newSocket();
        client = new SocketClient();
        client.setSocket(socket);
//        client.setTimeout(60 * 1000);

        eventHandler.onConnect(client);
        executorService.execute(new ClientHandler(client,eventHandler));


        Timer timer = new Timer();
        //5秒一次心跳包
        timer.schedule(new HeartbeatHandler(client),0, Const.CLIENT_HEARTBEAT_TIMES);
        client.setTimer(timer);

    }



    public SocketClient getClient() {
        return client;
    }
}
